const app = getApp()

const { SERVER_URL } = require('../../comm/script/config.js');

Page({
  data: {
    username: '',
    password: '',
    showRegister: false,
    regUsername: '',
    regPassword: '',
    regConfirmPassword: '',
    isLoggedIn: false
  },

  onLoad() {
    // 检查是否已登录
    const token = wx.getStorageSync('token');
    const username = wx.getStorageSync('username');
    if (token && username) {
      this.setData({ isLoggedIn: true, username });
    } else {
      this.setData({ isLoggedIn: false, username: '' });
    }
  },

  // 输入用户名
  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    })
  },

  // 输入密码
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    })
  },

  // 显示注册表单
  showRegisterForm() {
    this.setData({
      showRegister: true
    })
  },

  // 返回登录表单
  backToLogin() {
    this.setData({
      showRegister: false,
      regUsername: '',
      regPassword: '',
      regConfirmPassword: ''
    })
  },

  // 注册表单输入
  onRegUsernameInput(e) {
    this.setData({
      regUsername: e.detail.value
    })
  },

  onRegPasswordInput(e) {
    this.setData({
      regPassword: e.detail.value
    })
  },

  onRegConfirmPasswordInput(e) {
    this.setData({
      regConfirmPassword: e.detail.value
    })
  },

  // 提交注册
  onSubmitRegister() {
    const { regUsername, regPassword, regConfirmPassword } = this.data;
    console.log('注册参数:', regUsername, regPassword, regConfirmPassword);

    if (!regUsername || !regPassword || !regConfirmPassword) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    if (regPassword !== regConfirmPassword) {
      wx.showToast({
        title: '两次输入的密码不一致',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '注册中...'
    });

    wx.request({
      url: `${SERVER_URL}/api/register`,
      method: 'POST',
      data: {
        username: regUsername,
        password: regPassword
      },
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 201) {
          wx.showToast({
            title: '注册成功',
            icon: 'success',
            duration: 1500,
            success: () => {
              this.setData({
                showRegister: false,
                username: regUsername,
                password: '',
                regUsername: '',
                regPassword: '',
                regConfirmPassword: ''
              });
            }
          });
        } else {
          wx.showToast({
            title: res.data.message || '注册失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        console.error('注册失败:', error);
        wx.showToast({
          title: '注册失败，请检查网络',
          icon: 'none'
        });
      }
    });
  },

  // 登录
  onLogin() {
    const { username, password } = this.data

    if (!username || !password) {
      wx.showToast({
        title: '请输入用户名和密码',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '登录中...'
    })

    wx.request({
      url: `${SERVER_URL}/api/login`,
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        username,
        password
      },
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200 && res.data.token) {
          console.log('后端返回token:', res.data.token)
          wx.setStorageSync('token', res.data.token)
          console.log('本地存储token:', wx.getStorageSync('token'))
          wx.setStorageSync('userId', res.data.userId);
          wx.setStorageSync('username', this.data.username);
          console.log('登录成功 setStorageSync:', this.data.username);
          this.setData({ isLoggedIn: true, username: this.data.username }, () => {
            this.setData({ ...this.data }); // 强制刷新
          });
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500
          });
        } else {
          wx.showToast({
            title: res.data.message || '登录失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        console.error('登录失败:', error);
        wx.showToast({
          title: '登录失败，请检查网络',
          icon: 'none'
        });
      }
    });
  },

  logout() {
    wx.removeStorageSync('token');
    wx.removeStorageSync('userId');
    wx.removeStorageSync('username');
    this.setData({
      isLoggedIn: false,
      username: '',
      password: ''
    });
  },

  onReady: function () {

  },

  onShow() {
    const token = wx.getStorageSync('token');
    const username = wx.getStorageSync('username');
    console.log('onShow token:', token, 'username:', username);
    if (token && username) {
      this.setData({ isLoggedIn: true, username }, () => {
        this.setData({ ...this.data }); // 强制刷新
      });
    } else {
      this.setData({ isLoggedIn: false, username: '' }, () => {
        this.setData({ ...this.data });
      });
    }
  },

  onHide: function () {

  },

  onUnload: function () {

  },

  onPullDownRefresh: function () {

  },

  onReachBottom: function () {

  },

  onShareAppMessage: function () {

  }
}) 